﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using RIS.Models;
using System.Configuration;
using System.Data.SqlClient;
using System.Net;
using System.IO;

namespace RIS.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid && model.UserName!=null && model.Password!=null)
            {
                //Connect to our database
                helpers.con c = helpers.getConnection();

                //Get User with parameters
                c.command.CommandText = "SELECT * FROM users where username=@username AND password=@password";
                c.command.Parameters.Add(new SqlParameter("@username", model.UserName));
                c.command.Parameters.Add(new SqlParameter("@password", helpers.GetSHA512(model.Password)));

                SqlDataReader r = c.command.ExecuteReader();


                if (r.HasRows)
                {
                    //Read data from query
                    r.Read();

                    //Create a new 'user'
                    helpers.user u = new helpers.user();

                    //Add data to 'user'
                    u.username = r["username"].ToString();
                    u.password = r["password"].ToString();
                    u.email = r["email"].ToString();
                    u.ID = int.Parse(r["id"].ToString());

                    //Save to session
                    Session["loggeduser"] = u;

                    //Close connections
                    r.Close();
                    c.connection.Close();

                    //Return to homepage
                    return RedirectToAction("Dashboard", "Account");

                }

                else { ModelState.AddModelError("errorLogin", "Username and or password inncorect!"); }

            }

            else 
            { 
                
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            // Clear session
            Session["loggeduser"] = null;
            helpers.Send("b.andra.claudia@gmail.com", "hello", "you are so awesome");
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                bool valid = true;

                //check if the user already exists
                if (helpers.checkDbExistence("users", "username", model.UserName))
                {
                    valid = false;
                    ModelState.AddModelError("errorUsername", "This username already exists in our database!");
                }

                //check if the email already exists
                if (helpers.checkDbExistence("users", "email", model.Email))
                {
                    valid = false;
                    ModelState.AddModelError("errorEmail", "This email already exists in our database!");
                }
                //if everything is ok add user to db
                if (valid)
                {
                    helpers.con c = helpers.getConnection();

                    c.command.CommandText = "INSERT INTO users (username,password,email) VALUES (@rusername,@rpassword,@remail);SELECT SCOPE_IDENTITY()";
                    c.command.Parameters.Add(new SqlParameter("@rusername", model.UserName));
                    c.command.Parameters.Add(new SqlParameter("@rpassword", helpers.GetSHA512(model.Password)));
                    c.command.Parameters.Add(new SqlParameter("@remail", model.Email));

                    //Get last ID
                    Int64 lastId =Convert.ToInt64(c.command.ExecuteScalar());

                    c.connection.Close();

                    //Register user
                    helpers.user u = new helpers.user();
                    u.username = model.UserName;
                    u.password = model.Password;
                    u.email = model.Email;
                    u.ID = lastId;


                    Session["loggeduser"] = u;

                    return RedirectToAction("Dashboard", "Account");
                }

               


            }
            else { ViewBag.register = "error"; }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        public ActionResult Dashboard() 
        {
            return View();
        }

        public ActionResult AddPhoto()
        {
            return View();
        }

        protected string MyString;
        [HttpPost]
        public ActionResult AddPhoto(HttpPostedFileBase file)
        {
            System.IO.Stream stream;

            string token = helpers.GetSHA512((Session["loggeduser"] as helpers.user).ID.ToString());

            if (file != null && file.ContentLength > 0)
            {
                var urlRequest = (HttpWebRequest)WebRequest.Create("http://www.hackathon.vertexarmy.org/monitor.php");
                urlRequest.Method = "POST";

                int fileLen = file.ContentLength;
                byte[] input = new byte[fileLen];

                stream = file.InputStream;

                stream.Read(input, 0, fileLen);

                // Copy the byte array into a string. 
                for (int i = 0; i < fileLen; i++)
                    MyString = MyString + input[i].ToString();

                string post="token='"+token+"'&file='"+MyString+"'";
                urlRequest.ContentLength = post.Length;
                urlRequest.ContentType = "application/x-www-form-urlencoded";

                StreamWriter writer = new StreamWriter(urlRequest.GetRequestStream()); // Here is the WebException thrown
                writer.Write(post);
                HttpWebResponse response = (HttpWebResponse)urlRequest.GetResponse();



                
            }



            return View();
            

            //DO something to save the images somewhere
            //return PartialView("_AddPhotoPartial");
        }
    }
}
